import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/task.dart';

class TaskSchedulePage extends StatefulWidget {
  final List<Task> tasks;
  final VoidCallback onTaskUpdate;

  const TaskSchedulePage({
    Key? key,
    required this.tasks,
    required this.onTaskUpdate,
  }) : super(key: key);

  @override
  _TaskSchedulePageState createState() => _TaskSchedulePageState();
}

class _TaskSchedulePageState extends State<TaskSchedulePage> {
  // 当前选中的日期
  late DateTime _selectedDate;
  late List<DateTime> _weekDays;
  final TextEditingController _searchController = TextEditingController();
  
  // 总时长（小时和分钟）
  int _totalHours = 9;
  int _totalMinutes = 45;

  @override
  void initState() {
    super.initState();
    _selectedDate = DateTime.now();
    _generateWeekDays();
    _calculateTotalDuration();
  }

  // 生成当前周的日期列表
  void _generateWeekDays() {
    final now = DateTime.now();
    final firstDayOfWeek = now.subtract(Duration(days: now.weekday - 1));
    
    _weekDays = List.generate(7, (index) => 
      firstDayOfWeek.add(Duration(days: index))
    );
  }

  // 计算当天任务总时长
  void _calculateTotalDuration() {
    // 实际应用中应该根据任务时间计算真实的总时长
    // 这里只是示例
    _totalHours = 9;
    _totalMinutes = 45;
  }

  // 按小时分组任务
  Map<int, List<Task>> _getTasksByHour() {
    // 过滤当天的任务
    final todayTasks = widget.tasks.where((task) {
      final taskDate = task.time;
      return taskDate.year == _selectedDate.year && 
             taskDate.month == _selectedDate.month && 
             taskDate.day == _selectedDate.day;
    }).toList();
    
    // 按小时分组
    final tasksByHour = <int, List<Task>>{};
    for (var task in todayTasks) {
      final hour = task.time.hour;
      if (!tasksByHour.containsKey(hour)) {
        tasksByHour[hour] = [];
      }
      tasksByHour[hour]!.add(task);
    }
    
    return tasksByHour;
  }

  @override
  Widget build(BuildContext context) {
    final tasksByHour = _getTasksByHour();
    
    return Scaffold(
      backgroundColor: Colors.grey[100],
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 搜索栏
            _buildSearchBar(),
            
            // 标题和日期
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 16.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    'Task',
                    style: TextStyle(
                      fontSize: 30,
                      fontWeight: FontWeight.bold,
                      color: Color(0xFF232751),
                    ),
                  ),
                  Row(
                    children: [
                      const Icon(Icons.calendar_today, size: 20),
                      const SizedBox(width: 4),
                      Text(
                        DateFormat('MMMM\nyyyy').format(_selectedDate),
                        style: const TextStyle(
                          fontSize: 14,
                          color: Color(0xFF232751),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            
            // 星期选择器
            _buildWeekDaySelector(),
            
            // 今日标题和总时间
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 16.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    'Today',
                    style: TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: Color(0xFF232751),
                    ),
                  ),
                  Text(
                    '$_totalHours h $_totalMinutes min',
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                      color: Color(0xFF232751),
                    ),
                  ),
                ],
              ),
            ),
            
            // 分割线
            const Divider(height: 1, thickness: 1, color: Color(0xFFEEEEEE)),
            
            // 按小时显示的任务列表
            Expanded(
              child: ListView.builder(
                itemCount: 24, // 24小时
                itemBuilder: (context, index) {
                  final hour = index;
                  final tasksAtHour = tasksByHour[hour] ?? [];
                  
                  // 如果没有任务且不是重要时段（早上7点到晚上10点），跳过
                  if (tasksAtHour.isEmpty && (hour < 7 || hour > 22)) {
                    return const SizedBox.shrink();
                  }
                  
                  return _buildHourSection(hour, tasksAtHour);
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 搜索栏
  Widget _buildSearchBar() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Container(
        height: 50,
        decoration: BoxDecoration(
          color: Colors.grey[200],
          borderRadius: BorderRadius.circular(25),
        ),
        child: TextField(
          controller: _searchController,
          decoration: InputDecoration(
            hintText: 'Search for task',
            hintStyle: TextStyle(color: Colors.grey[400]),
            prefixIcon: Icon(Icons.search, color: Colors.grey[400]),
            suffixIcon: _searchController.text.isNotEmpty
                ? IconButton(
                    icon: const Icon(Icons.clear, color: Colors.grey),
                    onPressed: () => setState(() => _searchController.clear()),
                  )
                : null,
            border: InputBorder.none,
            contentPadding: const EdgeInsets.symmetric(vertical: 15),
          ),
          onChanged: (value) {
            setState(() {});
          },
        ),
      ),
    );
  }

  // 星期选择器
  Widget _buildWeekDaySelector() {
    const daysAbbr = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'];
    
    return Container(
      height: 100,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: List.generate(7, (index) {
          final day = _weekDays[index];
          final isSelected = day.day == _selectedDate.day &&
              day.month == _selectedDate.month &&
              day.year == _selectedDate.year;
          
          return GestureDetector(
            onTap: () {
              setState(() {
                _selectedDate = day;
                _calculateTotalDuration();
              });
            },
            child: Container(
              width: 45,
              height: 80,
              decoration: BoxDecoration(
                color: isSelected ? const Color(0xFF5E6CF2) : Colors.transparent,
                borderRadius: BorderRadius.circular(16),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    daysAbbr[index],
                    style: TextStyle(
                      color: isSelected ? Colors.white : const Color(0xFF232751),
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 6),
                  Text(
                    day.day.toString(),
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: isSelected ? Colors.white : const Color(0xFF232751),
                    ),
                  ),
                ],
              ),
            ),
          );
        }),
      ),
    );
  }

  // 每小时任务区域
  Widget _buildHourSection(int hour, List<Task> tasks) {
    final formattedHour = hour.toString().padLeft(2, '0');
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 小时标题
        Padding(
          padding: const EdgeInsets.only(left: 20.0, top: 16.0),
          child: Text(
            '$formattedHour:00',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
              color: const Color(0xFF232751).withOpacity(0.8),
            ),
          ),
        ),
        
        // 任务列表
        if (tasks.isEmpty)
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 12.0),
            child: Row(
              children: [
                Text(
                  'You don\'t have any schedule',
                  style: TextStyle(color: Colors.grey[400]),
                ),
                const SizedBox(width: 10),
                TextButton.icon(
                  onPressed: () {
                    // 添加任务的逻辑
                  },
                  icon: const Icon(Icons.add, size: 16),
                  label: const Text('Add'),
                  style: TextButton.styleFrom(
                    foregroundColor: const Color(0xFF5E6CF2),
                    padding: EdgeInsets.zero,
                    visualDensity: VisualDensity.compact,
                  ),
                ),
              ],
            ),
          )
        else
          ListView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: tasks.length,
            itemBuilder: (context, index) {
              return _buildTaskItem(tasks[index]);
            },
          ),
        
        // 分割线
        const Divider(height: 1, thickness: 1, color: Color(0xFFEEEEEE)),
      ],
    );
  }

  // 单个任务项
  Widget _buildTaskItem(Task task) {
    // 根据优先级确定边框颜色
    Color borderColor;
    String priorityLabel = '';
    Color tagBgColor;
    
    switch (task.priority) {
      case 3:
        borderColor = Colors.red;
        priorityLabel = 'Urgent';
        tagBgColor = Colors.red.shade50;
        break;
      case 2:
        borderColor = Colors.orange;
        priorityLabel = 'Important';
        tagBgColor = Colors.orange.shade50;
        break;
      default:
        borderColor = Colors.blue;
        priorityLabel = 'Normal';
        tagBgColor = Colors.blue.shade50;
    }

    // 计算结束时间（示例：任务持续15分钟到35分钟）
    final endTime = task.time.add(Duration(minutes: 15 + (task.priority * 10)));
    final startTimeStr = DateFormat('HH:mm').format(task.time);
    final endTimeStr = DateFormat('HH:mm').format(endTime);

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 8.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 左侧彩色指示条
          Container(
            width: 4,
            height: 80,
            decoration: BoxDecoration(
              color: borderColor,
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          const SizedBox(width: 12),
          
          // 任务详情
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 标题和菜单按钮
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      task.title,
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                        color: Color(0xFF232751),
                      ),
                    ),
                    IconButton(
                      icon: const Icon(Icons.more_vert, size: 20),
                      padding: EdgeInsets.zero,
                      constraints: const BoxConstraints(),
                      onPressed: () {
                        // 显示操作菜单
                      },
                    ),
                  ],
                ),
                
                // 时间范围
                Text(
                  '$startTimeStr - $endTimeStr',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[500],
                  ),
                ),
                
                const SizedBox(height: 8),
                
                // 标签
                Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                      decoration: BoxDecoration(
                        color: tagBgColor,
                        borderRadius: BorderRadius.circular(20),
                      ),
                      child: Text(
                        priorityLabel,
                        style: TextStyle(
                          color: borderColor,
                          fontSize: 12,
                        ),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                      decoration: BoxDecoration(
                        color: Colors.blue.shade50,
                        borderRadius: BorderRadius.circular(20),
                      ),
                      child: const Text(
                        'Home',
                        style: TextStyle(
                          color: Colors.blue,
                          fontSize: 12,
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
} 